﻿///<reference path="../jquery-1.4.1.min.js" />

var question_element;
var question_productId;
function displayQuestion(container, productId, pageIndex) {
    question_element = container ? container : question_element;
    question_productId = productId ? productId : question_productId;
    pageIndex = pageIndex ? pageIndex : 1;
    var url = "/Products/Question/" + question_productId + "/" + pageIndex + "?r=" + Math.random();
    $.get(url,
       "", function (data, status) {
           var html = "";
           if (data.Items && data.Items.length > 0) {
               for (var i in data.Items) {
                   html += initial_item(data.Items[i]);
               }
               var pager = initial_Pager(question_productId, pageIndex, data.PageSize, data.Total);
               html += pager;

           } else { //empty
               html = "<div class=\"content\">There are no questions for this product.</div>";
           }
           question_element.html(html);
       }, "json");
}

function initial_item(data) {
    var template = "<div class=\"content\"><strong class=\"author\">{0}</strong>"
           + "<span class=\"date\">{1}</span>"
           + "<p>{2}</p>"
           + "{3}"
           + "</div>";
    var answer_template = "<div class=\"reply\"><strong>{0}</strong>:{1}</div>";
    var answer = "";
    if (data.Answer) {
        answer = $.format(answer_template, data.AnswerBy, data.Answer);
    }
    return $.format(template, data.QuestionBy, data.QuestionDate, data.Question, answer);
}

function initial_Pager(productId, cPageIndex, pageSize, total) {
    var html = " <div class=\"pagination\">";
    if (cPageIndex > 1) {
        html += "<a href='javascript:void(0);' onclick='javascript:displayQuestion(null," + productId + "," + (cPageIndex - 1) + ");'>Previous</a>";
    }
    else {
        html += "<a>Previous</a>";
    }
    var totalPageNumber = parseInt(total / pageSize) + (total % pageSize > 0 ? 1 : 0);
    for (var i = 1; i <= totalPageNumber; i++) {
        if (i == cPageIndex) {
            html += "<span class='current'>" + i + "</span>";
        } else {
            html += "<a href='javascript:void(0)' onclick='javascript:displayQuestion(null," + productId + "," + i + ");'>" + i + "</a>";
        }
    }
    if (cPageIndex < totalPageNumber) {
        html += "<a href='javascript:void(0);' onclick='javascript:displayQuestion(null," + productId + "," + (cPageIndex + 1) + ");'>Next</a>";
    } else {
        html += "<a>Next</a>";
    }
    html += "</div>";
    return html;
}